<?php
// @formatter:off
/**
 * @file Class.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-06-16 19:41:09 +0000 (Sun, 16 Jun 2013) $
 *
 * $Id: Class.php 72 2013-06-16 19:41:09Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0-BETA2/extensions/CTNoName/Class.php $
 */

define("WC_SPECIAL_TAG_FROM_NOWHERE",	"From:NOWHERE");
define("WC_SPECIAL_TAG_FROM_UNKNOWN",	"From:UNKNOWN");
define("WC_SPECIAL_TAG_NAME_NONAME",	"Name:NONAME");
define("WC_SPECIAL_TAG_NAME_UNKNOWN",	"Name:UNKNOWN");

$auxInfo = array(
	"name"		=> "Update Unnamed",
	"description"	=> "Allows profides special tags for person comix where their names and/or procedens is not known",
	"version"	=> "1.0",
	"url"		=> array(
		"title"		=> "wcomix:Extension:CTNoName",
		"href"		=> "http://wiki.daemonraco.com/wiki/Wcomix:Extension:CTNoName"
	),
	"author"	=> "Alejandro Dario Simi"
);
$wcExtensionInfo[] = $auxInfo;

$wcCronScripts["CTNoName"] = array_merge($auxInfo, array(
		"auto"		=> true,
		"enabled"	=> true,
		"class"		=> "CTNoName"
));

$wcSpecialTags[] = WC_SPECIAL_TAG_NAME_NONAME;
$wcSpecialTags[] = WC_SPECIAL_TAG_NAME_UNKNOWN;
$wcSpecialTags[] = WC_SPECIAL_TAG_FROM_NOWHERE;
$wcSpecialTags[] = WC_SPECIAL_TAG_FROM_UNKNOWN;

$wcDefaults["class-CTNoName"]		= array();
$wcDefaults["class-CTNoName"]["groups"]	= array();

// @formatter:on

//
// Loading cron.
// Warning: they only load when it is a shell execution.
// @{
if(!empty($_SERVER["SHELL"])) {
	class CTNoName extends WCCronTool {
		public static $TagNoFrom = WC_SPECIAL_TAG_FROM_NOWHERE;
		public static $TagNoName = WC_SPECIAL_TAG_NAME_NONAME;
		public static $TagFromPrefix = "From:";
		public static $TagNamePrefix = "Name:";
		//
		// Public methods.
		public function run($spacer = "") {
			$this->runNoName($spacer);
			$this->runNoFrom($spacer);
		}
		public function showHelp($spacer = "") {
			global $wcSpecialTags;
			//echo "{$spacer}This tool adds tag '{self::$TagNoName}' to any comics without
			// tags.\n\n";
			//echo "{$spacer}It requires no extra parameters.\n";
		}
		//
		// Protected methods.
		protected function loadOptions() {
			$this->_optionsLoaded = true;
		}
		protected function runNoFrom($spacer = "") {
			global $wcTagsHolder;
			global $wcSpecialTags;
			global $wcGroupsHolder;
			global $wcDefaults;
			global $wcDatabaseAccess;

			$db = WCConnection::Instance();
			$dbPrefix = $wcDatabaseAccess['prefix'];

			foreach($wcGroupsHolder->groups() as $group) {
				if(is_readable($group->root) && (($wcDefaults['class-CTNoName']["groups"] && in_array($group->id, $wcDefaults['class-CTNoName']["groups"]) || !$wcDefaults['class-CTNoName']["groups"]))) {
					echo "{$spacer}Checking group '{$group->name}' ({$group->id}) prefix '".self::$TagFromPrefix."*':\n";

					$tag = $wcTagsHolder->itemByName(self::$TagNoFrom, $group);
					if(!$tag) {
						$wcTagsHolder->create($group, self::$TagNoFrom);
						$tag = $wcTagsHolder->itemByName(self::$TagNoFrom, $group);
					}

					//
					// Removing tagged comics
					$stmt = null;
					$stmtId = __CLASS__."::".__FUNCTION__."[rselect]";
					if($db->has($stmtId)) {
						$stmt = $db->get($stmtId);
					} else {
						$query = "select  mem_comic,\n";
						$query .= "        count(*) as mem_count\n";
						$query .= "from    {$dbPrefix}tag_members\n";
						$query .= "where   mem_comic in (\n";
						$query .= "                select  mem_comic\n";
						$query .= "                from    {$dbPrefix}tag_members\n";
						$query .= "                where   mem_tag   = :tag\n";
						$query .= "                 and    mem_group = :group)\n";
						$query .= " and    mem_comic in (\n";
						$query .= "                select  mem_comic\n";
						$query .= "                from    wc_tag_members\n";
						$query .= "                                inner join wc_tags\n";
						$query .= "                                        on (mem_group = tag_group and mem_tag = tag_id)\n";
						$query .= "                where   mem_tag   <> :tag\n";
						$query .= "                 and    mem_group =  :group\n";
						$query .= "                 and    tag_name like :prefix)\n";
						$query .= " and    mem_group = :group\n";
						$query .= "group by mem_comic\n";
						$stmt = $db->prepare($stmtId, $query);
					}

					$params = array(
						":group" => $group->id,
						":tag" => $tag->id,
						":prefix" => self::$TagFromPrefix."%"
					);

					if($stmt->execute($params) && $stmt->rowCount() > 0) {
						foreach($stmt->fetchAll() as $row) {
							if($row["mem_count"] > 1) {
								global $wcComicsHolder;

								$comic = $wcComicsHolder->item($row["mem_comic"], $group);
								if($comic && $comic->ok()) {
									echo "{$spacer}\tRemoving '{$comic->name}' ({$comic->id}@{$comic->directory}) from '{$tag->name}'\n";
									$tag->removeComic($comic);
								}
							}
						}
					}
				}
			}
		}
		protected function runNoName($spacer = "") {
			global $wcTagsHolder;
			global $wcSpecialTags;
			global $wcGroupsHolder;
			global $wcDefaults;
			global $wcDatabaseAccess;

			$db = WCConnection::Instance();
			$dbPrefix = $wcDatabaseAccess['prefix'];

			foreach($wcGroupsHolder->groups() as $group) {
				if(is_readable($group->root) && (($wcDefaults['class-CTNoName']["groups"] && in_array($group->id, $wcDefaults['class-CTNoName']["groups"]) || !$wcDefaults['class-CTNoName']["groups"]))) {
					echo "{$spacer}Checking group '{$group->name}' ({$group->id}) prefix '".self::$TagNamePrefix."*':\n";

					$tag = $wcTagsHolder->itemByName(self::$TagNoName, $group);
					if(!$tag) {
						$wcTagsHolder->create($group, self::$TagNoName);
						$tag = $wcTagsHolder->itemByName(self::$TagNoName, $group);
					}

					//
					// Removing tagged comics
					$stmt = null;
					$stmtId = __CLASS__."::".__FUNCTION__."[rselect]";
					if($db->has($stmtId)) {
						$stmt = $db->get($stmtId);
					} else {
						$query = "select  mem_comic,\n";
						$query .= "        count(*) as mem_count\n";
						$query .= "from    {$dbPrefix}tag_members\n";
						$query .= "where   mem_comic in (\n";
						$query .= "                select  mem_comic\n";
						$query .= "                from    {$dbPrefix}tag_members\n";
						$query .= "                where   mem_tag   = :tag\n";
						$query .= "                 and    mem_group = :group)\n";
						$query .= " and    mem_comic in (\n";
						$query .= "                select  mem_comic\n";
						$query .= "                from    wc_tag_members\n";
						$query .= "                                inner join wc_tags\n";
						$query .= "                                        on (mem_group = tag_group and mem_tag = tag_id)\n";
						$query .= "                where   mem_tag   <> :tag\n";
						$query .= "                 and    mem_group =  :group\n";
						$query .= "                 and    tag_name like :prefix)\n";
						$query .= " and    mem_group = :group\n";
						$query .= "group by mem_comic\n";
						$stmt = $db->prepare($stmtId, $query);
					}

					$params = array(
						":group" => $group->id,
						":tag" => $tag->id,
						":prefix" => self::$TagNamePrefix."%"
					);

					if($stmt->execute($params) && $stmt->rowCount() > 0) {
						foreach($stmt->fetchAll() as $row) {
							if($row["mem_count"] > 1) {
								global $wcComicsHolder;

								$comic = $wcComicsHolder->item($row["mem_comic"], $group);
								if($comic && $comic->ok()) {
									echo "{$spacer}\tRemoving '{$comic->name}' ({$comic->id}@{$comic->directory}) from '{$tag->name}'\n";
									$tag->removeComic($comic);
								}
							}
						}
					}
				}
			}
		}
	}

}
?>